/**
 * Created by ls.c on 2016/11/4.
 */

import vue from 'vue'
/**
 * get请求
 * @param  {String} options.url   api地址
 * @param  {String} options.query qu
 * 测试：http://iot.test.atwulian.com
 * 正式：http://iot.atwulian.com //120.77.200.174
 */
let host = '..'

export function loadInterceptors () {

	vue.http.interceptors.push((request, next) => {

		request.headers.set('Authorization', localStorage.getItem("tokenKey"));

		next((response) => {
			return response
		});
	});


}


export function getjson ({ url, query }, commit) {
//const getjson = ({ url, query }, commit) => {
	loadInterceptors()
	if (commit) commit('START_LOADING')
	let _url
	if (query) {
		_url = host + `/${url}?${query}`
	} else {
		_url = host + `/${url}`
	}
	return vue.http.get(_url)
		.then((res) => {
			if (commit) commit('FINISH_LOADING')
			if (res.status >= 200 && res.status < 300) {
				return res.data//JSON.parse(res.data)
			}
			return Promise.reject(new Error(res.status))
		})
}

export function postjson ({ url, query }, commit) {

	loadInterceptors()

	if (commit) commit('START_LOADING')
	let _url = host + `/${url}`

	//设置请求头Content-Type的值为application/x-www-form-urlencoded
	vue.http.options.emulateJSON = true
	vue.http.options.credientials = true
	return vue.http.post(_url, query)
		.then((res) => {
			if (commit) commit('FINISH_LOADING')
			if (res.status >= 200 && res.status < 300) {
				return res.data
			}
			return Promise.reject(new Error(res.status))
		})

}

export function putjson ({ url, query }, commit) {

	loadInterceptors()
	if (commit) commit('START_LOADING')
	let _url = host + `/${url}`

	return vue.http.put(_url, query)
		.then((res) => {
			if (commit) commit('FINISH_LOADING')
			if (res.status >= 200 && res.status < 300) {
				return res.data
			}
			return Promise.reject(new Error(res.status))
		})
}

export function deljson ({ url, query }, commit) {

	loadInterceptors()
	if (commit) commit('START_LOADING')
	let _url = host + `/${url}/${query}`

	return vue.http.delete(_url)
		.then((res) => {
			if (commit) commit('FINISH_LOADING')
			if (res.status >= 200 && res.status < 300) {
				return res.data
			}
			return Promise.reject(new Error(res.status))
		})
}


